package org.jeecg.extra.aspect.annotation;

import lombok.SneakyThrows;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;

/**
 * 枚举类型验证.
 *
 * <p>只验证是否是枚举中的一个值</p>
 *
 * @param
 * @author chao.xie
 * @创建日期: 2024.01.09
 * @return null
 * @since 1.0.0
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumParam.Validator.class})
@Documented
public @interface EnumParam {

    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    // 待验证的枚举类
    Class<? extends Enum<?>> enumClass();

    // 是否允许为空. true 允许为空; false 不允许为空
    boolean allowNull() default false;

    class Validator implements ConstraintValidator<EnumParam, Object> {
        private Class<? extends Enum<?>> enumClass;
        private boolean allowNull;

        @Override
        public void initialize(EnumParam enumValue) {
            enumClass = enumValue.enumClass();
            allowNull = enumValue.allowNull();
        }

        @SneakyThrows
        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            // 是否允许为null 或者 ""
            if (value == null || value.equals("")) {
                return allowNull;
            }

            // 参照枚举类为空说明不校验直接返回true
            if (enumClass == null) {
                return Boolean.TRUE;
            }

            //校验是否为枚举类中的值
            Enum<?>[] enumConstants = enumClass.getEnumConstants();
            for (Enum<?> enumConstant : enumConstants) {
                if (value.equals(enumConstant.toString())) {
                    return Boolean.TRUE;
                }
            }

            return Boolean.FALSE;
        }
    }
}
